import { defineStore } from 'pinia'
import { ref } from 'vue'

/**
 * 工作空间管理Store
 * 支持多套配置保存，用户可以创建不同的工作场景
 */

export interface WorkspaceConfig {
  id: string
  name: string
  description: string
  icon: string
  color: string
  createdAt: string
  updatedAt: string
  config: {
    // 数据录入页面配置
    dataEntry?: {
      defaultLine?: string
      defaultPeople?: number
      autoCalculate?: boolean
      showFloatingBar?: boolean
    }
    
    // 报表分析配置
    reports?: {
      selectedFields?: string[]
      defaultDateRange?: string
      defaultFilters?: any
      sortOrder?: string[]
    }
    
    // 目标值管理配置
    targetManagement?: {
      defaultFilters?: any
      pageSize?: number
      autoRefresh?: boolean
    }
    
    // 预估值管理配置
    estimateManagement?: {
      defaultFilters?: any
      pageSize?: number
      showNextRun?: boolean
    }
    
    // 记录维护配置
    recordMaintenance?: {
      defaultFilters?: any
      pageSize?: number
      editMode?: 'inline' | 'drawer'
    }
    
    // 全局配置
    global?: {
      theme?: 'light' | 'dark'
      language?: 'zh-CN' | 'en-US'
      autoSave?: boolean
      notifications?: boolean
    }
  }
}

export const useWorkspaceStore = defineStore('workspace', () => {
  // 当前工作空间
  const currentWorkspace = ref<WorkspaceConfig | null>(null)
  
  // 所有工作空间
  const workspaces = ref<WorkspaceConfig[]>([])
  
  // 默认工作空间配置
  const defaultWorkspaceConfig: Omit<WorkspaceConfig, 'id' | 'createdAt' | 'updatedAt'> = {
    name: '默认工作空间',
    description: '系统默认配置',
    icon: 'office-building',
    color: '#409eff',
    config: {
      dataEntry: {
        autoCalculate: true,
        showFloatingBar: true
      },
      reports: {
        selectedFields: ['record_date', 'line_name', 'order_number', 'material_code', 'product_name', 'quantity', 'calculated_pph'],
        defaultDateRange: 'last7days'
      },
      global: {
        theme: 'light',
        language: 'zh-CN',
        autoSave: true,
        notifications: true
      }
    }
  }

  // 创建新工作空间
  function createWorkspace(config: Omit<WorkspaceConfig, 'id' | 'createdAt' | 'updatedAt'>): WorkspaceConfig {
    const now = new Date().toISOString()
    const workspace: WorkspaceConfig = {
      ...config,
      id: generateId(),
      createdAt: now,
      updatedAt: now
    }
    
    workspaces.value.push(workspace)
    saveWorkspacesToStorage()
    
    return workspace
  }

  // 更新工作空间
  function updateWorkspace(id: string, updates: Partial<WorkspaceConfig>) {
    const index = workspaces.value.findIndex(w => w.id === id)
    if (index !== -1) {
      workspaces.value[index] = {
        ...workspaces.value[index],
        ...updates,
        updatedAt: new Date().toISOString()
      }
      
      // 如果更新的是当前工作空间，同步更新
      if (currentWorkspace.value?.id === id) {
        currentWorkspace.value = workspaces.value[index]
      }
      
      saveWorkspacesToStorage()
    }
  }

  // 删除工作空间
  function deleteWorkspace(id: string) {
    const index = workspaces.value.findIndex(w => w.id === id)
    if (index !== -1) {
      workspaces.value.splice(index, 1)
      
      // 如果删除的是当前工作空间，切换到默认工作空间
      if (currentWorkspace.value?.id === id) {
        switchToDefaultWorkspace()
      }
      
      saveWorkspacesToStorage()
    }
  }

  // 切换工作空间
  function switchWorkspace(id: string) {
    const workspace = workspaces.value.find(w => w.id === id)
    if (workspace) {
      currentWorkspace.value = workspace
      localStorage.setItem('pph_current_workspace_id', id)
      
      // 应用工作空间配置
      applyWorkspaceConfig(workspace)
    }
  }

  // 切换到默认工作空间
  function switchToDefaultWorkspace() {
    let defaultWorkspace = workspaces.value.find(w => w.name === '默认工作空间')
    
    if (!defaultWorkspace) {
      defaultWorkspace = createWorkspace(defaultWorkspaceConfig)
    }
    
    switchWorkspace(defaultWorkspace.id)
  }

  // 应用工作空间配置
  function applyWorkspaceConfig(workspace: WorkspaceConfig) {
    // 应用全局配置
    if (workspace.config.global) {
      const globalConfig = workspace.config.global
      
      // 应用主题
      if (globalConfig.theme) {
        document.documentElement.setAttribute('data-theme', globalConfig.theme)
      }
      
      // 应用其他全局设置
      if (globalConfig.autoSave !== undefined) {
        localStorage.setItem('pph_auto_save', globalConfig.autoSave ? '1' : '0')
      }
      
      if (globalConfig.notifications !== undefined) {
        localStorage.setItem('pph_notifications', globalConfig.notifications ? '1' : '0')
      }
    }
    
    // 应用页面特定配置
    applyPageConfigs(workspace.config)
  }

  // 应用页面配置
  function applyPageConfigs(config: WorkspaceConfig['config']) {
    // 数据录入页面配置
    if (config.dataEntry) {
      if (config.dataEntry.showFloatingBar !== undefined) {
        localStorage.setItem('pph_show_floating_bar', config.dataEntry.showFloatingBar ? '1' : '0')
      }
    }
    
    // 其他页面配置可以在这里添加
  }

  // 保存当前状态到工作空间
  function saveCurrentStateToWorkspace(workspaceId?: string) {
    const targetId = workspaceId || currentWorkspace.value?.id
    if (!targetId) return
    
    const workspace = workspaces.value.find(w => w.id === targetId)
    if (!workspace) return
    
    // 收集当前状态
    const currentState = collectCurrentState()
    
    // 更新工作空间配置
    updateWorkspace(targetId, {
      config: {
        ...workspace.config,
        ...currentState
      }
    })
  }

  // 收集当前状态
  function collectCurrentState(): WorkspaceConfig['config'] {
    return {
      dataEntry: {
        showFloatingBar: localStorage.getItem('pph_show_floating_bar') === '1',
        autoCalculate: true // 可以从其他地方获取
      },
      global: {
        theme: document.documentElement.getAttribute('data-theme') as 'light' | 'dark' || 'light',
        autoSave: localStorage.getItem('pph_auto_save') === '1',
        notifications: localStorage.getItem('pph_notifications') === '1'
      }
    }
  }

  // 保存工作空间到localStorage
  function saveWorkspacesToStorage() {
    try {
      localStorage.setItem('pph_workspaces', JSON.stringify(workspaces.value))
    } catch (error) {
      console.warn('保存工作空间失败:', error)
    }
  }

  // 从localStorage加载工作空间
  function loadWorkspacesFromStorage() {
    try {
      const saved = localStorage.getItem('pph_workspaces')
      if (saved) {
        workspaces.value = JSON.parse(saved)
      }
      
      // 恢复当前工作空间
      const currentId = localStorage.getItem('pph_current_workspace_id')
      if (currentId) {
        const workspace = workspaces.value.find(w => w.id === currentId)
        if (workspace) {
          currentWorkspace.value = workspace
          applyWorkspaceConfig(workspace)
        } else {
          switchToDefaultWorkspace()
        }
      } else {
        switchToDefaultWorkspace()
      }
    } catch (error) {
      console.warn('加载工作空间失败:', error)
      switchToDefaultWorkspace()
    }
  }

  // 导出工作空间配置
  function exportWorkspace(id: string): string | null {
    const workspace = workspaces.value.find(w => w.id === id)
    if (workspace) {
      return JSON.stringify(workspace, null, 2)
    }
    return null
  }

  // 导入工作空间配置
  function importWorkspace(configJson: string): boolean {
    try {
      const config = JSON.parse(configJson)
      
      // 验证配置格式
      if (!config.name || !config.config) {
        throw new Error('无效的工作空间配置格式')
      }
      
      // 生成新ID避免冲突
      createWorkspace({
        ...config,
        name: `${config.name} (导入)`
      })
      
      return true
    } catch (error) {
      console.error('导入工作空间失败:', error)
      return false
    }
  }

  // 生成唯一ID
  function generateId(): string {
    return Date.now().toString(36) + Math.random().toString(36).substring(2)
  }

  // 初始化
  function initialize() {
    loadWorkspacesFromStorage()
  }

  return {
    // 状态
    currentWorkspace,
    workspaces,
    
    // 方法
    createWorkspace,
    updateWorkspace,
    deleteWorkspace,
    switchWorkspace,
    switchToDefaultWorkspace,
    saveCurrentStateToWorkspace,
    exportWorkspace,
    importWorkspace,
    initialize
  }
})
